﻿var EmployeesListPage = function(pageContainer, loadType) {
    EmployeesListPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    var employeesToShow = 20;
    var employeesIndex = 0;
    var lastLetter = "";
    var myScroll = null;
    var isLoading = false;
    var selectionCallback = null;
    var searchBar = null;
    var searchResultsInfo = null;
    var searchBarContainer = null;
    var filter = null;
    var allEmployees = [];

    this.LoadTypes = {
        All: 1,
        Subordinates: 2
    };

    this.LoadType = loadType || this.LoadTypes.Subordinates;

    var Elements = {
        employeesList: pageContainer.find(".employeesList"),
        pullUp: pageContainer.find(".pullUp"),
        loader: pageContainer.find(".loadMore")
    };

    var Templates = {
        employeesTemplate: pageContainer.find(".employeeTemplate"),
        employeesTemplateCompiled: null
    };

    this.setSelectionCallback = function(callback) {
        selectionCallback = callback;
        if (selectionCallback)
            app.Phone.setBackbtnVisible(true);
    };

    self.initialize = override(self.initialize, function() {
        self.Title = translate('Module_Title_EmployeeList');
        addSearchBar();
        addResultsInfo(Elements.employeesList);
        Elements.loader.show();
        app.translatePage(app.Pages.EmployeesList);

        pageContainer.bind('onBeforePageShow', function() {
            var isBackButtonVisible = selectionCallback != null || !app.HasPageChangedFromMenu;
            app.Phone.setBackbtnVisible(isBackButtonVisible);
        });

        pageContainer.bind('onPageShow', function() {
            self.CanGoBack = true;
        });

        pageContainer.bind('onPageHide', function() {
            selectionCallback = null;
        });

        $(document).bind('changedCompany', function() {
            resetList();
        });

        self.getPullUpData();
    });

    var resetList = function() {
        Elements.employeesList.empty();
        allEmployees = [];
        employeesIndex = 0;
        lastLetter = "";
        Elements.loader.show();
    };

    var addResultsInfo = function(element) {
        element.before($("#searchResultsInfoTemplate").html());
        var searchResultsInfoContainer = pageContainer.find(".search-results-container");
        searchResultsInfo = new SearchResultsInfo(searchResultsInfoContainer);
        searchResultsInfo.hide();
    };

    var addSearchBar = function() {
        pageContainer.find('.content').prepend($("#searchBarTemplate").html());
        searchBarContainer = pageContainer.find(".search-bar:first");

        filter = new EmployeesFilter(pageContainer.find('.filtru'));
        searchBar = new SearchBar(searchBarContainer, true, filter);
        searchBar.initialize();
        searchBar.setPlaceholderText(translate('ListaAngajati_Search_Placeholder'));

        searchBarContainer.show();

        searchBarContainer
            .bind('getData', function(e) {
                if (filter.isAnyDialogVisible())
                    return;

                var filterData = filter.getFilterData();

                if (e.Data.reset)
                    resetList();

                filter.hide();

                self.getPullUpData();
            })
            .bind('cancel', function(e) {
                if (filter.isAnyDialogVisible())
                    return;
                filter.reset();
                filter.hide();

                resetList();
                self.getPullUpData();
            }).bind('settings', function(e) {
                if (filter.isAnyDialogVisible())
                    return;

                filter.toggle();
            });
    };

    this.getPullUpData = function(callback) {
        if (isLoading)
            return;

        isLoading = true;

        var searchText = searchBar.getSearchText();

        var filterData = filter.getFilterData() || {};
        var pct_id = filterData.punctDeLucru ? filterData.punctDeLucru.Id : null;
        var dpt_id = filterData.departament ? filterData.departament.Id : null;
        var fnc_id = filterData.functie ? filterData.functie.Id : null;

        if (self.LoadType == self.LoadTypes.Subordinates)
            app.TMMService.General.GetSubordinatesList(employeesIndex, employeesToShow, searchText, pct_id, dpt_id, fnc_id, true, function(response) { handleEmployeesResponse(response, callback); });
        else if (self.LoadType == self.LoadTypes.All)
            app.TMMService.General.GetSalariatiSimple(new Date().getFullYear(), new Date().getMonth() + 1, employeesIndex, employeesToShow, searchText, null, pct_id, dpt_id, fnc_id, null, null, null, null, true, null, function(response) { handleEmployeesResponse(response, callback); });
    };

    var handleEmployeesResponse = function(response, callback) {
        $(document).trigger('hidePullDown');
        Elements.loader.hide();

        if (response && response.FinalResult) {
            if (!response.FinalResult.length || (employeesIndex == 0 && response.FinalResult.length < employeesToShow))
                Elements.loader.hide();
            else if (!employeesIndex)
                Elements.loader.show();

            employeesIndex += response.FinalResult.length;
            addEmployeesToList(response.FinalResult);

            if (callback)
                callback(true);
        } else app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));

        isLoading = false;
    };

    var addEmployeesToList = function(employees) {
        if (!employees || !employees.length)
            return;

        if (!Templates.employeesTemplateCompiled) {
            var source = Templates.employeesTemplate.html();
            Templates.employeesTemplateCompiled = Handlebars.compile(source);
        }

        var html = "";
        for (var i = 0; i < employees.length; i++) {
            var emp = employees[i];
            allEmployees.push(emp);
            if (emp.Name[0] != lastLetter) {
                lastLetter = emp.Name[0];
                html += "<div class='lista-angajati-letter'>" + lastLetter + "</div>";
            }

            emp.Picture = Utils.getEmployeePhoto(emp.HasPicture ? emp.PRS_ID : 0, emp.CNP);
            html += Templates.employeesTemplateCompiled(emp);
        }
        Elements.employeesList.append(html);
        addActionsOnEmployee();
    };

    var addActionsOnEmployee = function() {
        Elements.employeesList.find(".lista-angajati-item").unbind().click(function(e) {
            var index = Elements.employeesList.find(".lista-angajati-item").index($(this));
            if (index < 0)
                return;

            var employee = allEmployees[index];
            if (selectionCallback)
                return selectionCallback(employee);

            if (employee) {
                if (!app.Pages.EmployeeInfo.instance)
                    app.Pages.EmployeeInfo.instance = new EmployeeInfoPage(app.Pages.EmployeeInfo.container);
                app.Pages.EmployeeInfo.instance.refresh(employee.PRA_ID);
                app.changePage(app.Pages.EmployeeInfo);
            }

            return Event.stopEvent(e);
        });
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(ModuleActions.None);
    });

    this.goBack = function() {
        if (filter.isAnyDialogVisible())
            return filter.closeDialogs();
        if (filter.isVisible())
            return filter.hide();
        app.changePage(app.getPageByHash(self.LastPageHash));
    };

    this.getPullDownData = function() {
        resetList();
        Elements.loader.hide();
        self.getPullUpData();
    };

    this.refresh = function(shouldReset) {
        if (shouldReset)
            searchBar.reset();
        else self.getPullDownData();
    };

    this.isAnyDialogOpen = override(self.isAnyDialogOpen, function() {
        if (filter) {
            if (filter.isVisible())
                return true;
            return filter.isAnyDialogVisible();
        }

        return false;
    });

    self.initialize();
};
extend(EmployeesListPage, TMMobilePage);